package com.heiye.oss.biz.service.impl;

import com.heiye.framework.common.response.Response;
import com.heiye.framework.common.util.JsonUtils;
import com.heiye.oss.biz.constant.MQConstants;
import com.heiye.oss.biz.model.dto.UserAvatarMqDTO;
import com.heiye.oss.biz.service.FileService;
import com.heiye.oss.biz.strategy.FileStrategy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.heiye.framework.biz.context.thread.LoginUserContextHolder;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

/**
 * @author: heiye
 * @date: 2024/11/21 下午1:37
 * @version: v1.0.0
 * @description: TODO
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileStrategy fileStrategy;

    private static final String BUCKET_NAME = "heiye-interact";

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 上传文件
     *
     * @param avatar
     * @return
     */
    @Override
    public Response<?> uploadAvatar(MultipartFile avatar) {
        // 上传文件
        String url = fileStrategy.uploadAvatar(avatar, BUCKET_NAME);

        // 构建消息体 MqDTO
        UserAvatarMqDTO userAvatarMqDTO = UserAvatarMqDTO.builder()
                .userId(LoginUserContextHolder.getUserId())
                .avatarUrl(url)
                .updateTime(LocalDateTime.now())
                .build();

        // 构建消息对象，并将 DTO 转成 Json 字符串设置到消息体中
        Message<String> message = MessageBuilder.withPayload(JsonUtils.toJsonString(userAvatarMqDTO)).build();

        // 发送主题 Topic
        String destination = MQConstants.TOPIC_USER_AVATAR_UPLOAD;

        log.info("==> 开始发送关注操作 MQ, 消息体: {}", userAvatarMqDTO);

        // 异步发送 MQ 消息，提升接口响应速度
        rocketMQTemplate.asyncSend(destination, message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("==> MQ 发送成功，SendResult: {}", sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("==> MQ 发送异常: ", throwable);
            }
        });

        return Response.success(url);
    }
}
